import { createAsyncThunk, createSlice, PayloadAction,Action } from '@reduxjs/toolkit'

// 为 slice state 定义一个类型
interface CounterState {
  value: number,
  status: string
}

// 使用该类型定义初始 state
const initialState: CounterState = {
  value: 0,
  status: ""
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state: CounterState) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decrement: (state: CounterState) => {
      state.value -= 1
    },
    incrementByAmount: (state: CounterState, action: PayloadAction<number>) => {
      state.value += action.payload
    },
  },
  extraReducers(builder) {
    builder.addCase(incrementAsync.pending, (state: CounterState, action) => {
      state.status = "loading"
    }).addCase(incrementAsync.fulfilled, (state: CounterState, action:any) => {
      state.status = 'succeeded'
      let value = state.value
      const { payload  } = action
      state.value = value + payload
      console.log(action);
    })
  },
})

export const incrementAsync = createAsyncThunk("counter/incrementAsync", async () => {
  const getCount = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(2)
      }, 2000);
    })
  }
  let res = await getCount()
  return res
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer